const cv = require('opencv');

function getHistogram(mat) {
  let arr = [];
  for (var i = 0; i < 64; i++) {
      arr[i] = 0;
  }
  let pow4 = Math.pow(4, 2);
  let data = mat.toBuffer(); 
  for (var i = 0, len = data.length; i < len; i += 4) {
      var red = (data[i] / 64) | 0;
      var green = (data[i + 1] / 64) | 0;
      var blue = (data[i + 2] / 64) | 0;
      var index = red * pow4 + green * 4 + blue;
      arr[index]++;
  }

  return arr;
}

function cosine(arr1, arr2) {
  var axb = 0,
      a = 0,
      b = 0;
  for (var i = 0, len = arr1.length; i < len; i++) {
      axb += arr1[i] * arr2[i];
      a += arr1[i] * arr1[i];
      b += arr2[i] * arr2[i];
  }
  return axb / (Math.sqrt(a) * Math.sqrt(b));
} 

module.exports = { 
  'test1' : function (browser) {
    

    let sourcePath = './screenshots/a.png';
    let tempPath = './screenshots/b.png';
    cv.readImage(sourcePath, (err, sourceImg) => {
      if (err) return console.error('error loading image');
      let result = sourceImg.matchTemplate(tempPath, 5);
      // console.log("获得：" + result);
      // console.log('top left:', result[1], result[2], ' top right: ', result[1] + result[3], result[2]);
      // console.log('bottom left:', result[1], result[2] + result[4], ' bottom right: ', result[1] + result[3], result[2] + result[4]);
      // sourceImg.rectangle([result[1], result[2]],[result[1] + result[3], result[2]],
      //   [result[1], result[2] + result[4]],[ result[1] + result[3], result[2] + result[4]]);
      // sourceImg.save('./screenshots/test.png');
      // 截取结果图 与 b 图进行对比 最终获得一个百分比相似度
      let newMat = sourceImg.crop(result[1], result[2], result[3], result[4]);
      cv.readImage(tempPath, (error, tempImg) => {
        if (error) return console.error('error loading image');

        let per = cosine(getHistogram(newMat),getHistogram(tempImg));
        newMat.save('./screenshots/test.png');
        console.log('相似度：' , per); 
      });

      console.log('over');
    });
    browser.end();

  },
  'test2': browser => {
    browser
      .maximizeWindow()
      .url('https://www.baidu.com')
      .waitForElementVisible('body', 1000)
      .setValue('#kw', '衷于栖')
      .click('#su')
      .pause(3000)
      .assert.containsText('#wrapper_wrapper', '衷于栖')
      .saveScreenshot('./screenshots/fileName.png')
      .end();
  }
};